package com.hyperfix.simulator.timer;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author JiangChunYu
 * 2024/3/12
 */
@Component
public class CronTaskRegistrar implements DisposableBean {

    private final Map<Integer, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16);

    @Resource
    private TaskScheduler taskScheduler;

    public void addCronTask(SysJob task, String cronExpression) {
        Integer jobId = task.getJobId();
        if (this.scheduledTasks.containsKey(jobId)) {
            removeCronTask(jobId);
        }
        this.scheduledTasks.put(jobId, scheduleCronTask(new CronTask(task, cronExpression)));
    }

    public void removeCronTask(Integer jobId) {
        ScheduledTask scheduledTask = this.scheduledTasks.remove(jobId);
        if (scheduledTask != null)
            scheduledTask.cancel();
    }

    public ScheduledTask scheduleCronTask(CronTask cronTask) {
        ScheduledTask scheduledTask = new ScheduledTask();
        scheduledTask.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());

        return scheduledTask;
    }

    @Override
    public void destroy() {
        for (ScheduledTask task : this.scheduledTasks.values()) {
            task.cancel();
        }

        this.scheduledTasks.clear();
    }
}
